import { Sequelize } from 'sequelize';
import { createRequire } from 'module';
import UserModel from './User.js';
import EssayModel from './Essay.js';

const require = createRequire(import.meta.url);
const dbConfig = require('../config/database.cjs');

const env = process.env.NODE_ENV || 'development';
const config = dbConfig[env];

// 创建Sequelize实例
const sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  port: config.port,
  dialect: config.dialect,
  logging: config.logging,
  pool: config.pool,
  define: config.define,
  timezone: config.timezone,
});

// 初始化模型
const User = UserModel(sequelize, Sequelize.DataTypes);
const Essay = EssayModel(sequelize, Sequelize.DataTypes);

// 设置模型关联
User.associate({ Essay });
Essay.associate({ User });

// 测试数据库连接
async function testConnection() {
  try {
    await sequelize.authenticate();
    console.log('✅ Database connection established successfully.');
  } catch (error) {
    console.error('❌ Unable to connect to the database:', error.message);
    throw error;
  }
}

// 导出模型和连接
export { sequelize, Sequelize, User, Essay, testConnection };

export default {
  sequelize,
  Sequelize,
  User,
  Essay,
  testConnection,
};

